<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>


    <!-- CSS files start -->

    <link rel="stylesheet" href="/landlord/css/paggingAndPullRefresh.css"/>

    <link href="/landlord/css/details_all.css" rel="stylesheet" type="text/css" media="all"/>



    <script type="text/javascript">

        top.top.setTitle("我的房源");

    </script>

</head>
<body>

<%--

<div id="wrapper">
    <ul id="display">
    </ul>
</div>
--%>


<div class="ac-content" style="position: absolute;z-index: 600">
    <div id="J-page" class="ac-page-dd">
        <div class="ac-page-nav">
            <p class="ac-page-cur">1</p>
            <p class="ac-page-total">10</p>
        </div>
        <i class="ac-page-top"></i>
    </div>
</div>


<div class="websiteWrapper">


    <!-- page wrapper starts -->

    <div class="pageWrapper portfolioOnePageWrapper">


        <!-- portfolio wrapper starts -->

        <div class="portfolioOneWrapper" id="wrapper" style="left: 0;">


            <!-- portfolio item starts  -->

            <ul id="display" style="">

            </ul>

        </div>
    </div>
</div>

<%--使用缓存--%>
<script src="/landlord/js/iscroll.js"></script>
<script type="text/javascript" src="/landlord/js/paggingAndPullRefresh_all.js"></script>


<%--删除事件--%>
<script type="text/javascript">


    //删除事件在前端进行维护.在点击删除按钮后,房间将会处于一种代移除状态,之后会等待三秒钟.如果超过三秒钟,撤销按钮随机消失


    //计时器
    let timers = [];


    $(document).on('click', '.singleProjectDeleteButton', function () {


        //找到编辑按钮并将其隐藏
        var del = $(this);

        //被删除元素的id
        var id = del.attr('href');

        del.parent().prev().hide();
        del.parent().prev().prev().hide();
        del.parent().before('<h2 id=removeMsg'+id+' class="removeMsg" style="color: #636281;text-align: center;padding-top: 80px;padding-bottom: 60px">五秒内可撤销(轻触立即删除)</h2>');
        del.next().hide();
        del.removeClass('singleProjectDeleteButton');
        del.addClass('singleProjectBackoutButton');
        del.text("撤销");


        function rm(){
            //发起删除请求
            $.post('/landlord/myRooms/remove', {id: id}, function () {
                let item = del.parent().parent().parent();
                item.slideUp(500, function () {
                    item.remove();
                    $J.totalSub(1);
                    myScroll.refresh();
                });
            });
        }

        $('#removeMsg' + id).click(function () {
            clearTimeout(timers[id]);
            rm();
        });


        timers[id] = setTimeout(function () {
            rm();
        }, 5000);

        //将计时器放入map

    });


    //对后加入的元素添加点击事件
    $(document).on('click', '.singleProjectBackoutButton', function () {


        var backout = $(this);

        var id = backout.attr('href');

        //移除计时器
        clearTimeout(timers[id]);

        backout.parent().parent().find('.removeMsg').remove();
        backout.parent().prev().show();
        backout.parent().prev().prev().show();
        backout.next().show();
        backout.addClass('singleProjectDeleteButton');
        backout.removeClass('singleProjectBackoutButton');
        backout.text("删除");

    });


</script>


<script type="text/javascript">


    var $J = $('#J-page');

    $J.pageination({
        always: false,
        startPos: 60,
        stepHeight: 500,
        total: 0
    });


    initParam = {
        id: "wrapper",
        pullDownAction: Refresh,
        pullUpAction: Load,

        scroll: function (y) {
            $J.onScroll(y);
        },

        scrollEnd: function (y) {
            $J.scrollEnd(y);
        }

    };

    refresher.init(initParam);


    $J.on('click.top', function (event) {
        $J.onScroll(myScroll.startY);
        refresher.myScroll.scrollTo(0, myScroll.minScrollY, 1000, false);
    });


    var ul = $("#display");
    var cPage = 1;
    var tPageSize = 3;

    function Refresh() {
        $.post('/landlord/myRooms', {page: 1, pageSize: tPageSize}, function (result) {
            ul.empty();
            append(result);
            $J.updateTotal(result.length);
            cPage = 2;
            myScroll.refresh();
        });

    }


    function Load() {

        $.post('/landlord/myRooms', {page: cPage, pageSize: tPageSize}, function (result) {
            append(result);
            $J.totalAdd(result.length);
            cPage++;
            myScroll.refresh();
        });
    }


    function searchSec(result, q) {


        //更改标题
        top.top.setTitle("搜索结果");

        //更改标记位
        isSearch = true;

        ul.empty();

        $J.updateTotal(result.length);

        append(result);

        cPage = 1;

        myScroll.refresh();

        refresher.myScroll.scrollTo(0, myScroll.minScrollY, 1000, false);


        //修改加载方法

        initParam.pullUpAction = function () {


            var q = args.q;

            //使用ajax进行请求

            args.addition.page = cPage;

            q = q + '&' + $.param(args.addition, true);

            $.ajax({
                method: args.method,
                type: args.type,
                url: args.url,
                data: q,
                success: function (result) {
                    append(result);
                    $J.totalAdd(result.length);
                    cPage++;
                    myScroll.refresh();
                },
                error: function () {
                    alert("加载失败");
                }
            });

        };


        initParam.pullDownAction = function () {
            var q = args.q;

            //使用ajax进行请求
            args.addition.page = 1;

            q = q + '&' + $.param(args.addition, true);

            $.ajax({
                method: args.method,
                type: args.type,
                url: args.url,
                data: q,
                success: function (result) {
                    ul.empty();
                    append(result);
                    $J.updateTotal(result.length);
                    cPage = 2;
                    myScroll.refresh();
                },
                error: function () {
                    alert("加载失败");
                }
            });

        };

    }


    var isSearch = false;

    //开启搜索
    var args = {
        method: 'post',
        addition: { //附加参数
            fields: ['name', 'location'],
            page: 1,
            pageSize: tPageSize
        },
        url: '/landlord/myRooms/search',
        onsuccess: searchSec
    };
    top.searchAble(args);

    //房间插入模板
    function append(ls) {

        for (var i in ls) {


            let imgUrl;


            if (ls[i].images && ls[i].images.length > 0) {
                //TODO 图片URL
                imgUrl = '/resource/preview/2/' + ls[i].images[0] + '.jpg';
            }
            else {
                //产生一个随机数从缺省图片中选出一张
                imgUrl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546502159888&di=ba8195972eb78359422bb19a4e6b59d1&imgtype=0&src=http%3A%2F%2Fp2.so.qhimgs1.com%2Ft01481b7750ea1d245e.png';

            }

            var s = '' +
                '                <li id=' + "room_" + ls[i].id + ' style="height: 500px;;width :96%;left: 0;margin-left: 2%;padding-top:20px;background-color: transparent;line-height: 15px">' +
                '' +
                '' +
                '                    <div class="portfolioOneItemWrapper" style="max-height: 495px;">' +
                '                        <a href=' + "/landlord/roomDetails?id=" + ls[i].id + ' target="_blank" class="portfolioOneItemImageWrapper"><img' +
                '                                style="max-height: 300px;object-fit: cover;width: 100%"' +
                '                                src="' + imgUrl + '" alt=""/></a>' +
                '                        <div class="portfolioOneItemInfoWrapper" style="max-height: 200px">' +
                '                            <h3 class="portfolioOneItemTitle">' + ls[i].name + '</h3>' +
                '                            <div>' + ls[i].location.address + ',' + ls[i].location.detailedDescription + '</div>' +
                '                        </div>' +
                '                        <div class="portfolioOneItemButtonsWrapper">' +
                '                            <a href="' + ls[i].id + '" onclick="return false" class="singleProjectDeleteButton">删除</a>' +
                '                            <a class="portfolioOneEditButton" target="_blank" href=' + "/landlord/edit?id=" + ls[i].id + ' >编辑</a>' +
                '                        </div>' +
                '                    </div>' +
                '' +

                '' +
                '                </li>                ';

            ul.append(s);
        }

    }


    Refresh();

</script>


<%--重新获取焦点时从cookie中获取变化的数据--%>
<script  src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<script type="text/javascript">


    window.onfocus = function () {

        let deleteRoomId = $.cookie('deleteRoomId');

        let editRoomId = $.cookie('editRoomId');

        let putRoomId = $.cookie('putRoomId');


        if (deleteRoomId) {

            $.cookie('deleteRoomId', '');

            let item = $('#room_' + deleteRoomId);

            item.slideUp(500, function () {
                item.remove();
                $J.totalSub(1);
            });

        }


        if (putRoomId) {

            //无论是否请求成功都将该putRoomId移除
            $.cookie('putRoomId', '');

            //如果有新添加的房间

            if (!isSearch) {//如果非搜索状态

                $.post('/landlord/myRooms/get', {id: putRoomId}, function (room) {
                    let imgUrl;

                    if (room.images && room.images.length > 0) {
                        //TODO 图片URL
                        imgUrl = '/resource/preview/2/' + room.images[0] + '.jpg';

                    }
                    else {
                        //let random = Math.floor(Math.random() * 14) + 1;
                        imgUrl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546502159888&di=ba8195972eb78359422bb19a4e6b59d1&imgtype=0&src=http%3A%2F%2Fp2.so.qhimgs1.com%2Ft01481b7750ea1d245e.png';

                    }

                    var s = '' +
                        '                <li id=' + "room_" + room.id + ' style="height: 500px;;width :96%;left: 0;margin-left: 2%;padding-top:20px;background-color: transparent;display: none;line-height: 15px">' +
                        '' +
                        '' +
                        '                    <div class="portfolioOneItemWrapper" style="max-height: 480px;">' +
                        '                        <a href=' + "/landlord/roomDetails?id=" + room.id + ' target="_blank" class="portfolioOneItemImageWrapper"><img' +
                        '                                style="max-height: 300px;object-fit: cover;width: 100%"' +
                        '                                src="' + imgUrl + '" alt=""/></a>' +
                        '                        <div class="portfolioOneItemInfoWrapper" style="max-height: 150px">' +
                        '                            <h4 class="portfolioOneItemTitle">' + room.name + '</h4>' +
                        '                            <div >' + room.location.address + ',' + room.location.detailedDescription + '</div>' +
                        '                        </div>' +
                        '                        <div class="portfolioOneItemButtonsWrapper">' +
                        '                            <a href="' + room.id + '" onclick="return false" class="singleProjectDeleteButton">删除</a>' +
                        '                            <a class="portfolioOneEditButton" target="_blank" href=' + "/landlord/edit?id=" + room.id + ' >编辑</a>' +
                        '                        </div>' +
                        '                    </div>' +
                        '' +

                        '' +
                        '                </li>';

                    ul.prepend(s);
                    $J.totalAdd(1);

                    var n = $("#room_" + room.id);

                    if ($('.ac-page-cur').text() === '1') {
                        n.slideDown(600, function () {
                            myScroll.refresh();
                        });

                    } else {

                        //滚动到顶端
                        refresher.myScroll.scrollTo(0, refresher.myScroll.minScrollY, 1000, false);

                        setTimeout(function () {
                            n.slideDown(500, function () {
                                myScroll.refresh();
                            });
                        }, 1000);
                    }
                });

            }

        }


        if (editRoomId) {

            $.cookie('editRoomId', '');

            let item = $('#room_' + editRoomId);

            //首先判断当前列表中是否还具有该房源
            if (item) {

                //在具有该房源的前提下
                $.post('/landlord/myRooms/get', {id: editRoomId}, function (room) {

                    //首先隐藏原数据
                    item.slideUp(300, function () {

                        //修改数据

                        let imgUrl;

                        if (room.images && room.images.length > 0) {
                            //TODO 图片URL
                            imgUrl = '/resource/preview/2/' + room.images[0] + '.jpg';
                        }
                        else {
                            let random = Math.floor(Math.random() * 14) + 1;
                            //产生一个随机数从缺省图片中选出一张
                            imgUrl = '/landlord/images/vacant/' + random + ".jpg";
                        }

                        //图片的url
                        item.find('img').replaceWith('<img style="max-height: 300px;object-fit: cover;width: 100%" src=' + imgUrl + '>');


                        //房间名称
                        var name = item.find('.portfolioOneItemTitle');

                        name.next().replaceWith('<div>' + room.location.address + ',' + room.location.detailedDescription + '</div>');

                        name.replaceWith('<h4 class="portfolioOneItemTitle">' + room.name + '</h4>')

                        //再以将数据显示出来
                        item.slideDown(300);
                    });

                });


            }

        }


    };


</script>


</body>
</html>